<?php

/**
 * Created on 2010-09-13
 *
 * @desc		数据库链接
 * 
 * @author 		micah <micah.shi@gmail.com>
 * @package 	protected.src
 */
class ConnectionFactory {
	private static $instance = null;
	public $connection = null;
	
	/**
	 * @desc 新建数据库连接
	 * @return PDO
	 */
	public function getConnection() {
		if($this->connection){
			return $this->connection;
		}
		$config = $this->getDBConfig ();
		$dns = sprintf ( 'mysql:host=%s;dbname=%s', $config ['host'], $config ['dbname']);
		$this->connection = new PDO ( $dns, $config ['dbuser'], $config ['password'], array (PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true ) );
		$this->connection->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
		$this->connection->exec ( 'set names '.$config['charset'] );
		return $this->connection;
	}
	
	/**
	 * 根据当前运行级别,返回数据库配置
	 *
	 * @return array
	 */
	public function getDBConfig() {
		if (empty ( $config )) {
			$path = dirname ( __FILE__ ) . '/../../config/database.php';
			$config = include($path);
		}
		return $config;
	}
	
	public static function getInstance() {
		if (! self::$instance) {
			self::$instance = new ConnectionFactory ();
		}
		return self::$instance;
	}
}
?>